import router from '@/router/index'
import { isNavigationFailure, NavigationFailureType } from 'vue-router'
import type { RouteRecordRaw, RouteLocationRaw } from 'vue-router'
import { ElNotification } from 'element-plus'
import { useConfig } from '@/stores/config'
import { closeShade } from '@/utils/pageShade'

/**
 * 导航失败有错误消息的路由push
 * @param to — 导航位置，同 router.push
 */
export const routePush = async (to: RouteLocationRaw) => {
  try {
    const failure = await router.push(to)
    if (isNavigationFailure(failure, NavigationFailureType.aborted)) {
      ElNotification({
        message: 'utils。导航失败，导航卫士拦截！',
        type: 'error'
      })
    } else if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
      // ElNotification({
      //   message: 'utils。导航失败，在导航目标位置！',
      //   type: 'warning'
      // })
    }
  } catch (error) {
    ElNotification({
      message: 'utils。导航失败，路线无效！',
      type: 'error'
    })
    console.error(error)
  }
}

/**
 * 获取第一个菜单
 */
export const getFirstRoute = (routes: RouteRecordRaw[], menuType = 'tab'): false | RouteRecordRaw => {
  const routerPaths: string[] = []
  const routers = router.getRoutes()
  routers.forEach((item) => {
    if (item.path) routerPaths.push(item.path)
  })
  let find: boolean | RouteRecordRaw = false
  for (const key in routes) {
    if (routes[key].meta?.type == 'menu' && routes[key].meta?.menu_type == menuType && routerPaths.indexOf(routes[key].path) !== -1) {
      return routes[key]
    } else if (routes[key].children && routes[key].children?.length) {
      find = getFirstRoute(routes[key].children!)
      if (find) return find
    }
  }
  return find
}

/**
 * 打开侧边菜单
 * @param menu 菜单数据
 * @param plaid
 * @param appid
 */
export const onClickMenu = (menu: RouteRecordRaw, plaid: string, appid: string) => {
  if (menu.meta?.url && typeof menu.meta.url === 'string') {
    window.open(menu.meta.url)
  } else {
    routePush({ path: menu.path, query: { p: plaid, appid } })
    const config = useConfig()
    if (config.layout.mobile) {
      closeShade(() => {
        config.setLayout('menuCollapse', true)
      })
    }
  }
}
